package dfs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 给定一个无重复元素的数组 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。
 * https://leetcode-cn.com/problems/combination-sum/
 *
 * @author: luo
 * @email: luo@nyist.edu.cn
 * @date: 2021/1/25 18:53
 */
public class CombinationSum {
    public static void main(String[] args) {
        int[] candidates = {2, 3, 6, 7};
        int target = 7;
        List<List<Integer>> lists = combinationSum(candidates, target);
        System.out.println(lists);
    }

    private static List<List<Integer>> list = new LinkedList<>();

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {

//        backtracking(0, target, candidates, new LinkedList<>(), 0);
        Arrays.sort(candidates);
        backtracking(target, candidates, new LinkedList<>(), 0);
        return list;
    }

    private static void backtracking(int n, int target, int[] candidates, LinkedList<Integer> nums, int index) {
        if (n == target) {
            list.add(new ArrayList<>(nums));
        } else if (n < target) {
            for (int i = index; i < candidates.length; i++) {
                nums.addLast(candidates[i]);
                backtracking(n + candidates[i], target, candidates, nums, i);
                nums.removeLast();
            }
        }
    }

    private static void backtracking(int n, int[] candidates, LinkedList<Integer> nums, int index) {
        if (n == 0) {
            list.add(new ArrayList<>(nums));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (candidates[i] > n) break;
            nums.addLast(candidates[i]);
            backtracking(n - candidates[i], candidates, nums, i);
            nums.removeLast();
        }

    }

}
